package com.website.dayouziblog.task;

import com.alibaba.fastjson.JSONObject;
import com.website.dayouziblog.mapper.dayouziblog.ArticleMapper;
import com.website.dayouziblog.model.DO.ArticleDO;
import com.website.dayouziblog.model.VO.ArticleVO;
import com.website.dayouziblog.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 用于获取热点数据放入redis的定时任务类（已作废，现通过Quartz来对定时任务进行管理）
 */
@Component
public class GetHotDataTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetHotDataTask.class);

    @Resource
    private ArticleMapper articleMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${key.article_expireTime}")
    private Integer article_expireTime;

    /**
     * 获取热点数据
     */
    public void getData(){
        LOGGER.info("开始获取热点数据");
        try {
            List<ArticleDO> allArticle = articleMapper.findAllArticle();
            for (ArticleDO articleDO : allArticle) {
                ArticleVO articleVO = JSONObject.parseObject(JSONObject.toJSONString(articleDO), ArticleVO.class);
                HashMap map = JSONObject.parseObject(JSONObject.toJSONString(articleVO), HashMap.class);
                redisUtil.hmset("article_info:" + articleVO.getId(), map, article_expireTime);
            }
        } catch (Exception e){
            LOGGER.error("获取热点数据失败");
            e.printStackTrace();
        }
    }

    /**
     * 获取热点数据的定时任务
     * https://cron.qqe2.com/      cron表达式生成器
     */
//    @Scheduled(cron = "0/10 0/1 * * * ?")
    public void getDataSchedul(){
        LOGGER.info("定时任务开启");
        getData();
        LOGGER.info("定时任务结束");
    }

}
